package com.liangwj.springbootredis.RedisConfig;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * <b>Description:</b> 实战中我们还经常会在Redis中存储对象，<br/>
 * 这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。<br/>
 * 但是Spring Boot并不支持直接使用，需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化 <br />
 * @author Lingwenjun
 * @date 2018/12/14-14:02
 * @version 1.0
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {

    //
    private Converter<Object, byte[]> serializer = new SerializingConverter();
    //
    private Converter<byte[], Object> deseriallizer = new DeserializingConverter();
    //
    static final byte[] EMPTY_ARRAY = new byte[0];

    @Override
    public byte[] serialize(Object o) {
        if (null == o) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(o);
        } catch (Exception e) {
           return EMPTY_ARRAY;
        }

    }

    @Override
    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deseriallizer.convert(bytes);
        } catch (Exception e) {
            throw new SerializationException(" Cannot deserialize", e);
        }
    }

    private boolean isEmpty(byte[] bytes) {
        return (bytes == null || bytes.length == 0);
    }
}
